/*
 * Unidata Platform
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 *
 * Commercial License
 * This version of Unidata Platform is licensed commercially and is the appropriate option for the vast majority of use cases.
 *
 * Please see the Unidata Licensing page at: https://unidata-platform.com/license/
 * For clarification or additional options, please contact: info@unidata-platform.com
 * -------
 * Disclaimer:
 * -------
 * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
 * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
 * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
 * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
 * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
 */
package org.unidata.mdm.job.reindex.service.impl;

import java.util.List;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.unidata.mdm.core.service.MetaModelService;
import org.unidata.mdm.core.type.model.RegisterElement;
import org.unidata.mdm.core.type.model.RelationElement;
import org.unidata.mdm.job.reindex.configuration.ReindexJobConfigurationConstants;
import org.unidata.mdm.meta.configuration.Descriptors;
import org.unidata.mdm.meta.service.impl.data.DataModelMappingComponent;
import org.unidata.mdm.meta.type.instance.DataModelInstance;

/**
 * @author Mikhail Mikhailov
 * Simple update data mapping writer.
 */
public class ReindexDataJobMappingItemWriter implements ItemWriter<String> {
    /**
     * Logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ReindexDataJobMappingItemWriter.class);
    /**
     * Drop or not.
     */
    @Value("#{jobParameters[" + ReindexJobConfigurationConstants.PARAM_CLEAN_INDEXES + "] ?: false}")
    private boolean forceCleanIndexes;
    /**
     * Meta model service
     */
    @Autowired
    private MetaModelService metaModelService;

    @Autowired
    private DataModelMappingComponent dataModelMappingComponent;
    /**
     * Constructor.
     */
    public ReindexDataJobMappingItemWriter() {
        super();
    }

    @Override
    public void write(List<? extends String> items) throws Exception {

        DataModelInstance i = metaModelService.instance(Descriptors.DATA);
        for (String entityName : items) {

            LOGGER.info("Processing {}.", entityName);

            // Default storage id will be taken
            dataModelMappingComponent.updateEntityMappings(null, forceCleanIndexes, entityName);
            if (i.isRegister(entityName)) {

                RegisterElement re = i.getRegister(entityName).getRegister();
                Stream<RelationElement> rels = Stream.concat(
                        re.getIncomingRelations().keySet().stream(),
                        re.getOutgoingRelations().keySet().stream());

                rels.forEach(r -> {
                    dataModelMappingComponent.updateRelationMappings(null, entityName, r.getName());
                });
            }
        }
    }
}
